from rest_framework import serializers
from .models import Questionnaire, Question, Answer
import json

class QuestionnaireSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questionnaire
        fields = '__all__'

class QuestionnaireListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questionnaire
        fields = ['id', 'title', 'qtype', 'description', 'status', 'created_at', 'updated_at']
        
class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = '__all__'

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = '__all__'

class QuestionnaireDetailSerializer(serializers.ModelSerializer):

    questions = QuestionSerializer(many=True, read_only=True)
    answers = serializers.SerializerMethodField()

    def get_answers(self, obj):
        user = self.context.get('request').user if 'request' in self.context else None
        ans = Answer.objects.filter(questionnaire=obj.id)
        if user:
            ans = ans.filter(user=user).first()  # 假设 Answer 模型有 user 字段
        return AnswerSerializer(ans).data

    class Meta:
        model = Questionnaire
        fields = ['id', 'title', 'qtype',
                  'description', 'status', 'version',
                  'created_at', 'updated_at', 'questions',
                  'answers']
        

class QuestionnaireDuoYuanSerializer(serializers.ModelSerializer):

    questions = serializers.SerializerMethodField() 
    answers = serializers.SerializerMethodField()
    body_type = serializers.SerializerMethodField()

    def get_body_type(self, obj):
        return self.context.get('body_type').body_type 

    def get_answers(self, obj):
        user = self.context.get('request').user
        ans = Answer.objects.filter(questionnaire=obj.id)
        if user:
            ans = ans.filter(user=user).first()  # 假设 Answer 模型有 user 字段
        return AnswerSerializer(ans).data

    def get_questions(self, obj):
        questions = obj.questions.filter(status=0).order_by('qnum')
        body_type = self.context.get('body_type') 
        # 写死！
        analysis = body_type.analysis
        risk = body_type.risk
        qdata = QuestionSerializer(questions, many=True).data 
        qdata[1]["title"] = f'{qdata[1]["title"]} \n"{body_type.body_type}:{analysis["text"]}"'
        qdata[2]["title"] = f'{qdata[2]["title"]} \n"{risk["module"]}:{risk["text"]}"'
        return qdata

    class Meta:
        model = Questionnaire
        fields = ['id', 'title', 'qtype',
                  'description', 'status', 'version',
                  'created_at', 'updated_at', 'questions',
                  'answers', 'body_type']
        
